import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

export interface ErrorHandlerOptions {
  showMessage?: boolean
  showDialog?: boolean
  autoLogout?: boolean
  redirectTo?: string
}

export function useErrorHandler() {
  const router = useRouter()
  const userStore = useUserStore()
  
  // 处理API错误
  const handleApiError = (error: any, options: ErrorHandlerOptions = {}) => {
    const {
      showMessage = true,
      showDialog = false,
      autoLogout = false,
      redirectTo
    } = options
    
    let message = '操作失败'
    let title = '错误'
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 400:
          message = data?.message || '请求参数错误'
          break
        case 401:
          message = '登录已过期，请重新登录'
          title = '认证失败'
          if (autoLogout) {
            userStore.logout()
            router.push('/login')
            return
          }
          break
        case 403:
          message = '没有权限执行此操作'
          title = '权限不足'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 422:
          message = data?.message || '数据验证失败'
          break
        case 500:
          message = '服务器内部错误，请稍后重试'
          break
        case 502:
        case 503:
        case 504:
          message = '服务暂时不可用，请稍后重试'
          break
        default:
          message = data?.message || `请求失败 (${status})`
      }
    } else if (error.request) {
      message = '网络连接失败，请检查网络设置'
      title = '网络错误'
    } else {
      message = error.message || '未知错误'
    }
    
    // 显示错误信息
    if (showDialog) {
      ElMessageBox.alert(message, title, {
        confirmButtonText: '确定',
        type: 'error'
      })
    } else if (showMessage) {
      ElMessage.error(message)
    }
    
    // 重定向
    if (redirectTo) {
      router.push(redirectTo)
    }
    
    // 记录错误日志
    console.error('API Error:', {
      error,
      message,
      timestamp: new Date().toISOString()
    })
  }
  
  // 处理业务逻辑错误
  const handleBusinessError = (message: string, options: ErrorHandlerOptions = {}) => {
    const { showMessage = true, showDialog = false } = options
    
    if (showDialog) {
      ElMessageBox.alert(message, '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
    } else if (showMessage) {
      ElMessage.warning(message)
    }
  }
  
  // 异步操作错误包装器
  const withErrorHandler = async <T>(
    asyncFn: () => Promise<T>,
    options: ErrorHandlerOptions = {}
  ): Promise<T | null> => {
    try {
      return await asyncFn()
    } catch (error) {
      handleApiError(error, options)
      return null
    }
  }
  
  return {
    handleApiError,
    handleBusinessError,
    withErrorHandler
  }
}